import { hexToRgb } from '@/utils/color'

export const DEFAULT_THEME = '#0323b5'
/** 跟新其他颜色 */
function updateOtherColor() {
  const root = document.documentElement
  const primaryRgb = root.style.getPropertyValue('--el-color-primary')
  // 从3到9更新浅色主色（i值越大，颜色越浅）
  for (let i = 3; i < 10; i++) {
    const lightVar = `--el-color-primary-light-${i}`
    const alpha = 1 - i / 10
    const lightColor = `rgba(${hexToRgb(primaryRgb)?.r}, ${hexToRgb(primaryRgb)?.g}, ${hexToRgb(primaryRgb)?.b}, ${alpha})`
    root.style.setProperty(lightVar, lightColor)
  }
}

/**
 * 设置主题颜色
 * @param theme 主题颜色
 */
export function setTheme(theme: string) {
  // 修改root变量
  const root = document.documentElement
  root.style.setProperty('--el-color-primary', theme)

  const fcRoot = document.documentElement.querySelector('._fc-r') as HTMLElement
  if (fcRoot) {
    fcRoot.style.setProperty('--el-color-primary', theme)
  }
  updateOtherColor()
  localStorage.setItem('app-theme-color', theme)
}

/**
 * 获取当前主题颜色
 * @returns 当前主题颜色
 */
export function getCurrentTheme(): string {
  const savedTheme = localStorage.getItem('app-theme-color') as any
  return savedTheme
}

/**
 * 初始化主题（页面加载时调用）
 */
export function initTheme() {
  const theme = getCurrentTheme()
  setTheme(theme)
}
